package org.dxy.domain.service.impl;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dxy.domain.port.repository.IWorkOrderRepository;
import org.dxy.domain.service.WorkOrderCodeGenerator;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.regex.Pattern;

/**
 * 工单编码生成器实现
 * @author dxy
 * @createTime 2025/9/16 23:45
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class WorkOrderCodeGeneratorImpl implements WorkOrderCodeGenerator {
    
    private final IWorkOrderRepository workOrderRepository;
    
    private static final String CODE_PREFIX = "WO-";
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd");
    private static final Pattern CODE_PATTERN = Pattern.compile("^WO-\\d{8}-\\d{3}$");
    
    @Override
    public String generateCode() {
        String dateStr = LocalDate.now().format(DATE_FORMATTER);
        String prefix = CODE_PREFIX + dateStr + "-";
        
        // 查找当天最大的序号
        int maxSequence = workOrderRepository.getMaxSequenceByDatePrefix(prefix);
        int nextSequence = maxSequence + 1;
        
        return prefix + String.format("%03d", nextSequence);
    }
    
    @Override
    public boolean validateCodeFormat(String code) {
        if (code == null || code.trim().isEmpty()) {
            return false;
        }
        
        return CODE_PATTERN.matcher(code.trim()).matches();
    }
    
    @Override
    public String getSuggestedCode() {
        return generateCode();
    }
}